package com.hub.realtime.common.utils;

import com.hub.realtime.common.model.MavenParams;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.resolution.DependencyRequest;
import org.eclipse.aether.util.graph.visitor.PreorderNodeListGenerator;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DownloadMavenJar {
    /**
     * 从指定maven地址下载指定jar包
     *
     * @param params
     * @throws ArtifactResolutionException
     */
    public static List<File> downLoadMavenJar(MavenParams params) throws Exception {

        List<File> fileList = new ArrayList<>();
        File file = new File(params.getTarget());
        if (!file.exists()) {
            file.mkdir();
        }
        RepositorySystem repoSystem = DependencyFactory.newRepositorySystem();
        RepositorySystemSession session = DependencyFactory.newSession(repoSystem, params.getTarget());
        RemoteRepository central = DependencyFactory.newRemoteRepository(params);

        //下载该jar包及其所有依赖jar包
        DefaultArtifact defaultArtifact = DependencyFactory.newDefaultArtifact(params.getArtifactId(), params.getGroupId(), params.getVersion());
        Dependency dependency = new Dependency(defaultArtifact,null,false,params.getExclusions());

//        if (params.getExclusions().size() > 0) {
//            dependency.setExclusions(params.getExclusions());
//        }

        CollectRequest collectRequest = new CollectRequest();
        collectRequest.setRoot(dependency);
        collectRequest.addRepository(central);
        DependencyNode node = repoSystem.collectDependencies(session, collectRequest).getRoot();
        DependencyRequest dependencyRequest = new DependencyRequest();
        dependencyRequest.setRoot(node);
        repoSystem.resolveDependencies(session, dependencyRequest);

        PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
        node.accept(nlg);
        fileList = nlg.getFiles();
        //此时就已经下载好了 打印出jars
        System.out.println(nlg.getFiles());
        return fileList;
    }


}

